import axios from 'axios';
// 转换post参数
import quertstring from 'querystring';
import proxy from '../config/host';
import type { tokenInfoType } from '@/interfaces';

const env = import.meta.env.MODE || 'development';

const API_HOST = env === 'mock' ? '/' : proxy[env].API; // 如果是mock模式 就不配置host 会走本地Mock拦截
// const API_HOST = env === 'development' ? '/' : proxy[env].API; // 如果是mock模式 就不配置host 会走本地Mock拦截

const CODE = {
  LOGIN_TIMEOUT: 1000000,
  REQUEST_SUCCESS: 0,
  REQUEST_FOBID: 1001,
};

const header = {
  'content-type': 'application/json',
  // 'Authorization': localStorage.getItem('access_token'),
  Authentication: localStorage.getItem('access_token'),
  'Access-Control-Allow-Origin': '*'
  
};

const instance = axios.create({
  baseURL: API_HOST,
  timeout: 100000,
  // withCredentials: true,
  headers: header,
});

// eslint-disable-next-line
// @ts-ignore
// axios的retry ts类型有问题
instance.interceptors.retry = 3;

// if (sessionStorage.getItem('tokenInfo') !== undefined && sessionStorage.getItem('tokenInfo') !== null) {
//   console.log('tokenInfo->',sessionStorage.getItem('tokenInfo'))
//   const tokenInfo: tokenInfoType = JSON.parse(sessionStorage.getItem('tokenInfo') as string);
//   instance.defaults.headers.common[tokenInfo?.tokenName as string] = tokenInfo?.tokenValue as string;
// }

if (localStorage.getItem('access_token') !== undefined && localStorage.getItem('access_token') !== null) {
  // console.log('access_token--->',localStorage.getItem('access_token'))
  instance.defaults.headers.common.access_token = localStorage.getItem('access_token');
}

// instance.interceptors.request.use((config) => config);
instance.interceptors.request.use((config) => {
  config.headers.Authentication = localStorage.getItem('access_token');
  // post 请求要处理下参数格式，
  // config.headers['Content-Type'] == multipart/form-data 上传文件接口，不需要重写
  // if (config.method === 'post') {
  //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  // }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      if (data.code === CODE.REQUEST_SUCCESS) {
        return data;
      }
      return response;
    }
  },
  (err) => {
    const { config } = err;

    console.log('config---->', config);

    if (!config || !config.retry) return Promise.reject(err);

    config.retryCount = config.retryCount || 0;

    if (config.retryCount >= config.retry) {
      return Promise.reject(err);
    }

    config.retryCount += 1;

    const backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve({});
      }, config.retryDelay || 1);
    });

    return backoff.then(() => instance(config));
  },
);

export default instance;
